package com.example.searchservice.controller;


import com.example.cloudcommon.util.RedisCacheUtil;
import com.example.searchservice.doc.UserDocument;
import com.example.searchservice.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/cache")
@Slf4j
public class CacheController {

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    private UserService userService;

    @GetMapping("/get/{id}")
    public ResponseEntity<?> setCache(@PathVariable String id) {
        UserDocument user = redisCacheUtil.getCacheObject(id);

        log.info("user:{}", user);

        if(user == null){
            user = redisCacheUtil.get(id, UserDocument.class, () -> {
                return userService.findById(id).get();
            }, 0);
        }

        return ResponseEntity.ok(user);
    }
}
